//
//  WorkingPDFVC.m
//  EditTabDemo
//
//  Created by lhy on 2021/2/26.
//  Copyright © 2021 lhy. All rights reserved.
//

#import "WorkingPDFVC.h"
#import "LMRPDFCollectionViewCell.h"
#import "LMRTabsView.h"
#import "LHYDefine.h"
#import "LMRPDFViewVC.h"
#import "LMRTabsScrollView.h"
#import "LMRPDFTaskAlertView.h"

#define PDF_WEIGHT              self.pdfCollectionView.frame.size.width
#define PDF_HEIGHT              self.pdfCollectionView.frame.size.height
#define PDF_BOUNDS              self.pdfCollectionView.frame


@interface WorkingPDFVC () <UICollectionViewDelegate, UICollectionViewDataSource, UIDocumentPickerDelegate>

/// 选项卡按钮
@property (nonatomic, strong) LMRTabsView *tabsView;
/// +添加文件
@property (nonatomic, strong) LMRTabsView *tabAddFileView;

@property (strong, nonatomic) NSMutableArray *tabBtnArr;
/// 数据源个数
@property (nonatomic, assign) NSInteger dataCount;
/// 当前下标
@property (nonatomic, assign) NSInteger currentIndex;

@property (strong, nonatomic) LMRTabsScrollView *tabScrollView;
/// 左右滚动view
@property (weak, nonatomic) IBOutlet UICollectionView *pdfCollectionView;
@property (weak, nonatomic) IBOutlet UIView *pdfContentView;
@property (nonnull, strong) UICollectionViewFlowLayout *layout;
@property (weak, nonatomic) IBOutlet UIView *tabContentView;

@property (weak, nonatomic) IBOutlet UIButton *lastBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

/// 编辑/保存
@property (weak, nonatomic) IBOutlet UIButton *editAndSaveBtn;
/// 绘制ing/注释ing
@property (weak, nonatomic) IBOutlet UIButton *drawAndAnnoBtn;

@property (nonatomic, strong) LMRPDFViewVC *pdfVC;
/// collectionView 空白页label
@property (nonatomic, strong) UILabel *lbBlank;
/// iCloud文件
@property (strong, nonatomic) UIDocumentPickerViewController *documentPickerViewController;

@end

@implementation WorkingPDFVC

@synthesize lastBtn, nextBtn, tabContentView;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.pdfCollectionView setNeedsLayout];
    [self.pdfCollectionView layoutIfNeeded];
    PDF_BOUNDS = self.pdfCollectionView.frame;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}

- (void)initThreePDF {
    NSURL *url = [NSURL fileURLWithPath:@"file:///Users/lhy/Library/Developer/CoreSimulator/Devices/BAA24165-B1E8-4A99-84D4-F6683E02E664/data/Containers/Shared/AppGroup/19F27F27-C267-4D9C-A913-C11044C30141/File%20Provider%20Storage/Document.pdf"];
    self.tabBtnArr = (NSMutableArray *)@[url, url, url];
    [self initUIWithData:self.tabBtnArr];
}

/// 上一步
- (IBAction)actionLastBtn:(UIButton *)sender {
    
}
/// 下一步
- (IBAction)actionNextBtn:(UIButton *)sender {
    LMRPDFTaskAlertView *alertView = [LMRPDFTaskAlertView sharePDFTaskAlertView];
    [alertView show];
}
/// PDF编辑/保存
- (IBAction)actionEditAndSave:(UIButton *)sender {
    
    if (self.dataCount <= 0) {
        return;
    }
    
    sender.selected = !sender.selected;
    
    [sender setTitle:sender.selected? @"保存" : @"编辑" forState:UIControlStateNormal];
    [sender setTitleColor:sender.selected? UIColor.systemBlueColor : UIColor.redColor forState:UIControlStateNormal];
    
//    self.btnClear.hidden = !_btnEdit.selected;
    self.drawAndAnnoBtn.hidden = !sender.selected;
    
    LMRPDFViewVC *subVC = self.childViewControllers[self.currentIndex];
    
    if (sender.selected) {

        [subVC enterDrawingWithBtn:self.drawAndAnnoBtn];
        [subVC.toolView show];
    } else {

        [subVC closeDrawingWithBtn:self.drawAndAnnoBtn];
        [subVC.toolView hide];
        // 退出绘制，立即保存
        [subVC actionSave];
    }
}
/// PDF绘制/注释
- (IBAction)actionDrawAndAnno:(UIButton *)sender {
    LMRPDFViewVC *subVC = self.childViewControllers[self.currentIndex];
    
    if ([sender.titleLabel.text isEqualToString:@"注释ing"]) {
        //画线
        [subVC enterDrawingWithBtn:sender];
    } else {
        //注释
        [subVC closeDrawingWithBtn:sender];
    }
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    _tabScrollView.frame = tabContentView.bounds;
    self.lbBlank.center = self.pdfCollectionView.center;
    //设置每个item减一大小
    self.layout.itemSize = CGSizeMake(PDF_WEIGHT, PDF_HEIGHT);
}
#pragma mark - UI
- (void)initUI {
    [tabContentView addSubview:self.tabScrollView];
    [self setPDFCollectionView];
    
    [self initThreePDF];
}


- (void)initUIWithData:(NSMutableArray *)dataArr {
    self.currentIndex = 0;
    [self.tabScrollView tabDeleteAll];
    
    for (int i = 0; i < dataArr.count; i++) {
        //新添加tab  对应新添加pdfVC
        LMRPDFViewVC *vc = [[LMRPDFViewVC alloc] init];
        vc.pdfURL = dataArr[i];
        [self addChildViewController:vc];
    }
    
    [self.tabScrollView initTabsScrollViewWithData:dataArr];
//    [self.tabScrollView initTabsScrollViewWithData:dataArr];
    [self.pdfCollectionView reloadData];
}

- (void)setPDFCollectionView {
    // 创建FlowLayout
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    //设置item间的最小间距
    self.layout.minimumInteritemSpacing = 0;
    //设置最小行间距
    self.layout.minimumLineSpacing = 0;
    //设置滚动方向
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    _pdfCollectionView.collectionViewLayout = self.layout;
    
    self.lbBlank = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.lbBlank.text = @"请添加文件";
    self.lbBlank.textAlignment = YES;
    [_pdfCollectionView addSubview:self.lbBlank];
    
    [_pdfCollectionView registerNib:[UINib nibWithNibName:@"LMRPDFCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"LMRPDFCollectionViewCell"];
}

- (void)addPDFDocumentFromFiles {
    
    NSArray *types = @[@"public.composite-content",
                       @"com.adobe.pdf"];
    self.documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
    
    self.documentPickerViewController.delegate = self;
    
    // Save changes
    
//    [self saveChages];
    
    [self presentViewController:self.documentPickerViewController animated:YES completion:nil];
}


#pragma mark - UICollectionViewDataSource
// 返回cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    self.lbBlank.hidden = self.dataCount;
    return self.dataCount;
    
//    self.lbBlank.hidden = self.tabBtnArr.count;
//    return self.tabBtnArr.count;
}
// 返回cell内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"LMRPDFCollectionViewCell";
    LMRPDFCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.titleSS.text = [NSString stringWithFormat:@"index:%ld", indexPath.row];
    
    
    for (UIView *view in cell.contentView.subviews) {
       [view removeFromSuperview];
    }
    
    CGRect rect = CGRectMake(0, 0, 944, 1104);
    rect = PDF_BOUNDS;
    LMRPDFViewVC *subVC = self.childViewControllers[indexPath.row];
    subVC.view.frame = rect;
    subVC.qlView.frame = rect;
    subVC.qlView.pdfView.frame = rect;
    
    [cell.contentView addSubview:subVC.qlView];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
// 选中某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    self.currentIndex = indexPath.row;
    NSLog(@"currentIndex: %ld", self.currentIndex);
}

#pragma mark - 打开iCloud UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    //获取授权
    NSLog(@"urls.firstObject:      %@", urls.firstObject);
    
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    
    if (fileUrlAuthozied) {
        [self.tabScrollView updateTabsScrollViewWithCount:self.dataCount];
    } else {
        NSLog(@"授权失败");
    }
}


- (LMRTabsScrollView *)tabScrollView {
    if (!_tabScrollView) {
        _tabScrollView = [[LMRTabsScrollView alloc] init];
        WeakSelf;
        _tabScrollView.tabsSelectedBlock = ^(NSInteger index, NSInteger dataCount) {
            StrongSelf;
            NSLog(@"TabsSelectedIndex:   %ld", index);
            strongSelf.currentIndex = index;
            [strongSelf.pdfCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        };
        ///打开 iCloud文件
        _tabScrollView.tabsOpenBlock = ^{
            StrongSelf;
            [strongSelf addPDFDocumentFromFiles];
        };
        _tabScrollView.tabsAddBlock = ^(NSInteger index, NSInteger dataCount) {
            StrongSelf;
            //新添加的 tab 对应新添加的 pdfVC
            strongSelf.pdfVC = [[LMRPDFViewVC alloc] init];
            [strongSelf addChildViewController:strongSelf.pdfVC];
            strongSelf.dataCount = dataCount;
            if (strongSelf.dataCount > 1) {
                //大于1个时先刷新当前选中的PDF，再执行reloadData添加新的（⚠️此处需要添加这句代码，否则reloadData会出现异常）
                [strongSelf.pdfCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:strongSelf.currentIndex inSection:0]]];
            }
            [strongSelf.pdfCollectionView reloadData];
        };
        _tabScrollView.tabsDeleteBlock = ^(NSInteger index, NSInteger dataCount) {
            StrongSelf;
            strongSelf.dataCount = dataCount;
            [strongSelf.pdfCollectionView reloadData];
            
            LMRPDFViewVC *vc = strongSelf.childViewControllers[index];
            [vc removeFromParentViewController];
            
            //删除选中项，将后一个置为选中
            if (index > 0) {
                index--;
            }
            //更新选中按钮
            [strongSelf.tabScrollView tabSelectedWithIndex:index];
        };
    }
    return _tabScrollView;
}

- (NSMutableArray *)tabBtnArr {
    if (!_tabBtnArr) {
        _tabBtnArr = [[NSMutableArray alloc] init];
    }
    return _tabBtnArr;
}

@end
